package cn.skyui.animator.feeds;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.util.Pair;
import android.support.v4.view.ViewCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.orhanobut.logger.Logger;
import com.windward.vii.library.data.constant.Constants;
import com.windward.vii.library.http.HttpObserver;
import com.windward.vii.library.http.RetrofitFactory;
import com.windward.vii.library.http.RxSchedulers;
import com.windward.vii.library.http.exception.ApiException;
import com.windward.vii.library.utils.SizeUtils;
import com.windward.vii.library.widget.recyclerview.GridSpacingItemDecoration;

import java.util.ArrayList;
import java.util.List;

import cn.skyui.animator.R;
import cn.skyui.animator.photo.Photo;
import cn.skyui.animator.photo.PhotoActivity;

public class FeedsActivity extends AppCompatActivity {

    Activity mActivity;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private RecyclerView mRecyclerView;
    private BaseQuickAdapter mAdapter;
    private Long lastId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity = this;
        setContentView(R.layout.activity_feeds);
        initData();
        initView();
        loadData();
    }


    private void initData() {
        lastId = 0L;
    }

    private void initView() {
        setSupportActionBar(findViewById(R.id.toolbar));
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        setTitle("主页");


        mSwipeRefreshLayout = findViewById(R.id.swipeLayout);
        mRecyclerView = findViewById(R.id.recyclerView);
        mSwipeRefreshLayout.setRefreshing(true);

        mRecyclerView.setLayoutManager(new GridLayoutManager(mActivity, 3, GridLayoutManager.VERTICAL, false));
        mRecyclerView.addItemDecoration(new GridSpacingItemDecoration(3, SizeUtils.dp2px(2f), false));
        mSwipeRefreshLayout.setColorSchemeColors(getResources().getColor(R.color.colorAccent));

        mAdapter = new BaseQuickAdapter<UgcItemVO, BaseViewHolder>(R.layout.layout_ugc_list_item, null) {
            @Override
            protected void convert(BaseViewHolder helper, UgcItemVO item) {
                String url = item.getType() == 1 ? item.getImage() : item.getCover();
                ImageView imageView = helper.getView(R.id.avatar);
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//                    imageView.setTransitionName(item.getId() + "-" + item.getIndex());
//                }
                Log.i("Feeds","transitionName = " + item.getId() + "-" + item.getIndex());
                ViewCompat.setTransitionName(imageView, item.getId() + "-" + item.getIndex());
                Glide.with(mContext).load(url).into((ImageView) helper.getView(R.id.avatar));
            }
        };

        mAdapter.setOnLoadMoreListener(this::loadData, mRecyclerView);
        mAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);

        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(final BaseQuickAdapter adapter, final View view, final int position) {
                List<UgcItemVO> items = adapter.getData();
                if (items.size() > 0) {
                    ArrayList<Photo> photoList = new ArrayList<>();
                    Pair<View, String>[] sharedElements = new Pair[items.size()];
                    int i = 0;
                    for (UgcItemVO vo : items) {
                        if (vo.getImage() != null) {
                            Photo photo = new Photo();
                            photo.id = vo.getId();
                            photo.index = vo.getIndex();
                            photo.url = vo.getImage();
                            photoList.add(photo);

                            Pair<View, String> p = Pair.create(view, vo.getId() + "-" + vo.getIndex());
                            sharedElements[i++] = p;
                        }
                    }
                    Intent intent = new Intent(mActivity, PhotoActivity.class);
                    intent.putExtra("position", position);
                    intent.putExtra("photoList", photoList);
                    ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation(mActivity, sharedElements);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                        mActivity.startActivity(intent, options.toBundle());
                    } else {
                        mActivity.startActivity(intent);
                    }
                }
            }
        });
        mSwipeRefreshLayout.setOnRefreshListener(() -> {
            initData();
            loadData();
        });

    }


    private void loadData() {
        RetrofitFactory.createService(ApiService.class)
                .ugcList(3960033l, lastId, Constants.DEFAULT_PAGE_SIZE)
                .compose(RxSchedulers.io2main())
                .subscribe(new HttpObserver<List<UgcItemVO>>() {
                    @Override
                    protected void onSuccess(List<UgcItemVO> list) {
                        mSwipeRefreshLayout.setRefreshing(false);

                        if(list.size() < Constants.DEFAULT_PAGE_SIZE) {
                            mAdapter.loadMoreEnd(false);
                        }  else {
                            mAdapter.loadMoreComplete();
                        }

                        if(list.size() > 0) {
                            List<UgcItemVO> wrapList = new ArrayList<>();
                            for(UgcItemVO itemVO : list) {
                                if(itemVO.getType() == 1) {
                                    JSONArray array = JSON.parseArray(itemVO.getImages());
                                    for(int i = 0; i < array.size(); i++) {
                                        UgcItemVO ugcItemVO = (UgcItemVO) itemVO.clone();
                                        if(ugcItemVO != null) {
                                            ugcItemVO.setImage(array.getString(i));
                                            ugcItemVO.setIndex(i);
                                            wrapList.add(ugcItemVO);
                                        }
                                    }
                                }
                            }

                            if (lastId == 0) {
                                mAdapter.setNewData(wrapList);
                            } else {
                                mAdapter.addData(wrapList);
                            }
                            lastId = list.get(list.size() - 1).getId();
                        }
                    }

                    @Override
                    protected void onFailure(ApiException e) {
                        super.onFailure(e);
                        mSwipeRefreshLayout.setRefreshing(false);
                        mAdapter.loadMoreFail();
                    }
                });
    }
}